import { Bar, Line, Pie, Doughnut } from 'react-chartjs-2'
import { commonOptions } from '../charts/chartConfig'
// 确保Chart.js组件被注册
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
  RadialLinearScale,
  Filler
} from 'chart.js'

// 注册所有需要的Chart.js组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
  RadialLinearScale,
  Filler
)

interface ChartData {
  type: 'chart'
  chartType: 'bar' | 'line' | 'pie' | 'doughnut'
  title: string
  description?: string
  data: {
    labels: string[]
    datasets: Array<{
      label: string
      data: number[]
      backgroundColor?: string | string[]
      borderColor?: string | string[]
      borderWidth?: number
      tension?: number
    }>
  }
  options?: any
}

interface ChartMessageProps {
  chartData: ChartData
}

export default function ChartMessage({ chartData }: ChartMessageProps) {
  const { chartType, title, description, data } = chartData

  // 合并默认选项和自定义选项
  const chartOptions = {
    ...commonOptions,
    plugins: {
      ...commonOptions.plugins,
      title: {
        display: true,
        text: title,
        font: {
          size: 14,
          weight: 'bold' as const
        },
        color: '#1e293b',
        padding: 10
      },
      legend: {
        ...commonOptions.plugins?.legend,
        display: chartType !== 'doughnut' // 环形图不显示图例
      }
    },
    ...chartData.options
  }

  const renderChart = () => {
    switch (chartType) {
      case 'bar':
        return <Bar data={data} options={chartOptions} />
      case 'line':
        return <Line data={data} options={chartOptions} />
      case 'pie':
        return <Pie data={data} options={chartOptions} />
      case 'doughnut':
        return <Doughnut data={data} options={chartOptions} />
      default:
        return <div className="text-red-500">不支持的图表类型: {chartType}</div>
    }
  }

  return (
    <div className="w-full max-w-md mx-auto">
      {/* 图表描述 */}
      {description && (
        <div className="mb-2 p-2 bg-slate-50 rounded-lg border-l-4 border-blue-500">
          <p className="text-xs text-slate-600">{description}</p>
        </div>
      )}
      
      {/* 图表容器 */}
      <div className="bg-white rounded-lg border border-slate-200 shadow-sm p-2">
        <div className="h-40 w-full">
          {renderChart()}
        </div>
      </div>
      
      {/* 图表信息 */}
      <div className="mt-1 text-xs text-slate-500 text-center">
        图表类型: {chartType} | 数据点: {data.labels.length}
      </div>
    </div>
  )
}
